import { ModalProps, TableColumnsType } from "antd"
import { useEffect, useState } from "react"
import styled from "styled-components"

import useApi from "@/api/member-manage"
import { IMemberInfo, IMemberPageLabelResponse } from "@/api/member-manage/types"
import { DataList } from "@/components/common"
import CommonModal from "@/components/common/modals"
import { useDataMapping, usePagination } from "@/hooks"
import { pageType } from "@/hooks/usePagination"
import { useLocale } from "@/locales"

const SNumberPeople = styled.div`
	color: #fb6260;
	padding: 0 20px;
`

const DialogGame = ({ record, ...props }: { record: IMemberPageLabelResponse } & ModalProps) => {
	const { newFormat, formatMessage } = useLocale()
	const [dataTable, setDataTable] = useState({} as Business.TableResourceType<IMemberInfo>)
	const { getMemberMemberInfoByLabelId, loading } = useApi()

	const { pagination, onPageChange, resetPagination } = usePagination(100)
	const { getFromDic } = useDataMapping()
	const columns: TableColumnsType = [
		{
			dataIndex: "userName",
			title: newFormat("common.member_number")
		},
		{
			dataIndex: "accountType",
			title: newFormat("common.number_type"),
			render: getFromDic("accountType", false)
		},
		{
			dataIndex: "merchantName",
			title: newFormat("common.belong_merchant")
		}
	]

	columns.forEach((item: any) => {
		item["align"] = "center"
		item["key"] = item.dataIndex
		item["titleText"] = item.title
	})

	const search = async (newPage?: pageType) => {
		const [err, data] = await getMemberMemberInfoByLabelId(
			newPage
				? {
						id: record.id,
						...newPage
				  }
				: {
						id: record.id,
						...pagination,
						pageNum: 1
				  }
		)

		if (err) return
		if (!newPage) resetPagination((pageInfo: pageType) => search(pageInfo))

		if (!err) setDataTable(data)
	}

	const handleOnPageChange = (page: { pageSize: number; current: number }) => {
		onPageChange(page)
		search({ pageSize: page.pageSize, pageNum: page.current })
	}

	useEffect(() => {
		search()
	}, [])

	return (
		<CommonModal width={960} title={formatMessage({ id: "member.number_of_people_adding_tags" })} footer={null} {...props}>
			<SNumberPeople>
				{formatMessage({ id: "member.label_name_to_configure" })} ： {record.labelName}
			</SNumberPeople>

			<DataList
				loading={loading}
				data={dataTable.record || []}
				columns={columns}
				pagination={{
					pageSize: dataTable.pageSize,
					current: dataTable.pageNum,
					total: dataTable.totalRecord,
					showSizeChanger: true
				}}
				size="middle"
				onChange={handleOnPageChange}
			/>
		</CommonModal>
	)
}

export default DialogGame
